<template>
  <div>
    <div>
      <FormPanel
        ref="formPanel"
        :list="formList"
        :cols="1"
        :formType="type"
        :isSubmitBtn="false"
        @formChange="formChangeHandle"
      />
      <el-form
        :model="botform"
        :rules="rules"
        ref="addSearchForm"
        size="mini"
        label-width="80px"
        inline-message
        >
        <el-form-item label="资讯模板" prop="contentType">
          <el-radio v-model="botform.contentType" :label="20141001">图文</el-radio>
        </el-form-item>
        <!-- 图文 -->
        <el-form-item label prop="content" v-show="botform.contentType==20141001">
          <!-- <quillEditor :uedata="botform.content" v-if="botform.contentType==20141001"  @clickevent="bizContentEdit"/> -->
          <!-- <quill-editor :uedata="botform.content"  @clickevent="bizContentEdit"/> -->
          <div class="contents" v-if="type === 'show'" style="height:350px;border: 1px solid #ccc;overflow:auto;" v-html="botform.content"></div>
          <Tinymce v-else v-model="botform.content" :height="300" actionUrl="/api/file/oss/upload"/>
        </el-form-item>
        <el-form-item v-if="type !== 'show'" label="" prop="disclaimer">
          <el-popover
            placement="top-start"
            title="免责声明"
            width="400"
            trigger="hover">
              <div style="border-top: 1px solid #eee;padding:'0';margin:'0';">
                <p>1. 本平台不对用户发布的任何内容(包括但不限于文章、图片、视频)的准确性进行保证。</p>
                <p>2. 用户需对所发表的内容负责，因所发表内容引发的一切纠纷，由该内容的发表者承担全部法律及连带责任。</p>
              </div>
            <el-radio v-model="radio" label="disclaimer" slot="reference">已阅读并同意<span style="color:#1588FF;">《免责声明》</span></el-radio>
          </el-popover>
        </el-form-item>
      </el-form>
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="preview('addSearchForm')">预 览</el-button>
      <el-button @click="closeDialog">取 消</el-button>
      <!-- <el-button v-if="type !== 'show'" :disabled="isDisabled" @click="saveDialog('addSearchForm','save')" type="primary">保 存</el-button>
      <el-button v-if="type !== 'show'" :disabled="isDisabled" @click="saveDialog('addSearchForm','release')" type="primary">发 布</el-button> -->
        <!-- <multiuse-button size="small" type="primary" :click="saveDialog('addSearchForm','save')" :auth-list="auths" auth-mark="/api/information/materiel/save">新增</multiuse-button> -->
        <multiuse-button v-if="type !== 'show'" :disabled="isDisabled" type="primary" :click="saveDialog.bind(this, 'addSearchForm','save')" :auth-list="auths" auth-mark="/api/information/materiel/save">保 存</multiuse-button>
        <multiuse-button v-if="type !== 'show'" :disabled="isDisabled" type="primary" :click="saveDialog.bind(this, 'addSearchForm','release')" :auth-list="auths" auth-mark="/api/information/materiel/release?id=${id}">发 布</multiuse-button>
    </div>
    <!--详情dialog-->
    <preview-dialog type="news" ref="preview-dialog" />
  </div>
</template>

<script>
import {
  saveNews,
  deleteNews,
  releaseNews,
  revokeNews,
 } from '@/api/community/news/index';
import { dictionary } from '@/utils/dictMixin';
import previewDialog from "@/components/community/previewDialog";
// import quillEditor from "@/components/quillEditor"; //调用编辑器
import { authority } from '@/utils/authMixin';

export default {
  name: 'NewsModal',
  mixins: [dictionary,authority],
  components: {
    previewDialog
  },
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.saveData = null;
    return {
      formList: this.createFormList(),
      radio: '',
      botform: {
        contentType: "",
        content: "",
        isFullpush: "",
      },
      rules: {
        contentType: [
          { required: true, message: "请选择资讯模版", trigger: "change" }
        ],
        // isRecommended: [
        //   { required: true, message: "请选择是否设为推荐", trigger: "change" }
        // ],
        content: [
          { required: true, message: "请编辑图文内容", trigger: "blur" }
        ]
      },
      isDisabled: false, //表单重复提交
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      if (this.type === 'edit' || this.type === 'show') {
        // 更新接口需要的记录 ID
        this.recordId = this.rowData.id;
        if (typeof this.rowData.titleImage !== 'object') {
          let arr = [];
          arr.push(this.rowData.titleImage)
          this.rowData.titleImage = arr
        }
        this.formList.forEach(x => {
          x.initialValue = this.rowData[x.fieldName];
        });
        this.botform = {
          contentType: this.rowData.contentType,
          content: this.rowData.content,
        }
        this.isDisabled = false
      }
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '标题',
          disabled: this.type === 'show'?true:false,
          fieldName: 'title',
          rules: [{ required: true, message: '请输入资讯标题', trigger: 'blur' }, { min: 1, max: 124, message: '长度在1到124个字符', trigger: 'blur' }]
        },
        {
          type: 'UPLOAD_IMG',
          label: '资讯图片',
          disabled: this.type === 'show'?true:false,
          fieldName: 'titleImage',
          placeholder: '请上传资讯图片',
          // style: { width: '250px' },
          rules: [{ required: true, message: '请上传资讯图片', trigger: 'change' }],
          upload: {
            actionUrl: '/api/file/oss/upload',
            fixedSize: [5, 2],
            isCalcHeight: true,
          }
        },
        {
          type: 'TEXT_AREA',
          rows: 4,
          label: '描述',
          disabled: this.type === 'show'?true:false,
          fieldName: 'newsSummary',
          placeholder: '请输入内容',
        },
        // {
        //   type: 'RADIO',
        //   label: '资讯模板',
        //   disabled: this.type === 'show'?true:false,
        //   fieldName: 'contentType',
        //   initialValue: '',
        //   itemList: [{value:20141001, text:'图文' }],
        //   rules: [{ required: true, message: '请选择资讯模版', trigger: 'blur' }],
        //   // change: val => {
        //   //   this.changeBrandSelect(val);
        //   // }
        // }
      ];
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    async saveDialog(formName,status) {
      this.$refs.formPanel.SUBMIT_FORM();
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.save(status)
        }else{
          this.$message.info("请填写必填项!");
          return false;
        }
      });

    },
    async save(status){
      this.isDisabled= true
      let data = {
        title: this.saveData.title,
        id: this.recordId,
        titleImage: this.saveData.titleImage[0],
        newsSummary: this.saveData.newsSummary,
        contentType: this.botform.contentType,
        thirdPartLink: this.saveData.thirdPartLink,
        isRecommended:this.saveData.isRecommended,
        isShow:10041001,
        content: this.botform.contentType == 20141003 ?
          JSON.stringify(this.saveData.photoList) : this.botform.content,
        status: status === "release"?20211002:20211001,
        sort: this.saveData.sort,
        isFullpush:this.saveData.isFullpush,
        radio: this.radio
        // radio: disclaimer
      };
      //是否全站推送
      if (this.saveData.isFullpush) {
        data.isFullpush = 10041001;
      } else {
        data.isFullpush = 10041002;
      }
      //校验主题图片是为空
      if (data.titleImage == null || data.titleImage == "") {
        this.$message.error("资讯图片不能为空!");
        return false;
      }
      // 校验是否选择免责声明
      if (status === "release" && (data.radio == null || data.radio == "")) {
        this.$confirm('请同意免责声明!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        this.isDisabled = false
        return false;
      }

      if (this.saveData !== null) {
        let res = await saveNews(data);
        if (res.resultCode === 200) {
          this.isDisabled = false
          this.closeDialog('refresh');
        } else {
          this.$message.error(res.errMsg);
          this.isDisabled = false
          return false
        }
      }
    },
    closeDialog(param) {
      this.$emit('close', false, param);
    },
    // 预览
    preview(formName) {
      let token = localStorage.getItem('token'),
        appId = localStorage.getItem('appId');
      // this.$refs['preview-dialog'].open('https://cscyx.yycsy.com/im_h5/cyx/news/index.html?userToken=1&newsId=50&appId=a689d54406b9c6ee&imChannel=Client')
      this.$refs.formPanel.SUBMIT_FORM();
      this.$refs[formName].validate(valid => {
        if (valid) {
          let data = {
            title: this.rowData.title,
            id: this.recordId,
            titleImage: this.rowData.titleImage[0],
            newsSummary: this.rowData.newsSummary,
            contentType: this.botform.contentType,
            content: this.botform.content,
            thirdPartLink: this.rowData.thirdPartLink,
            isRecommended:this.rowData.isRecommended,
            isShow: 10041001,
            content: this.botform.contentType == 20141003 ? JSON.stringify(this.rowData.photoList) : this.botform.content,
            status: 20211000,
            sort: this.rowData.sort,
            // radio: this.form.radio
          };
          //是否全站推送
          if (this.rowData.isFullpush) {
            data.isFullpush = 10041001;
          } else {
            data.isFullpush = 10041002;
          }
          //校验主题图片是为空
          if (data.titleImage == null || data.titleImage == "") {
            this.$message.error("资讯图片不能为空!");
            return false;
          }
          // 保存活动
          saveNews(data)
            .then(res => {
              // this.$message.success("保存成功!");
              if(res.data){
                this.rowData.id = res.data
              }
              let url = `${window.location.origin}/im_h5/cyx/news/index.html?userToken=${token}&previewId=${res.data}&appId=${appId}&imChannel=Client`
              // let url = `http://cscyx.yycsy.com/im_h5/cyx/news/index.html?userToken=${token}&previewId=${res.data}&appId=${appId}&imChannel=Client`
              this.$refs['preview-dialog'].open(url)
              // this.$emit('getList')
              // this.$refs.dialog.close()
            })
            .catch(err => {
              this.$message.info( "res.errMsg" );
              return false;
            });
        } else {
          this.$message.info("请填写必填项!");
          return false;
        }
      });
    },
  }
};
</script>

<style lang="less" scoped>
</style>
